<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" style="width: 500px" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option :label="tm.tmName" :value="tm.id" v-for="tm in tradeMarkList" :key="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" rows="5" placeholder="描述" style="width: 500px" v-model="spu.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <!-- 上传图片 -->
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImgList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unSelectSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
          <el-option :label="unSelect.name" :value="`${unSelect.id}:${unSelect.name}`" v-for="unSelect in unSelectSaleAttr" :key="unSelect.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" style="margin-left: 10px" :disabled="!attrIdAndAttrName" @click="addSaleAttr">添加销售属性</el-button>
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="width">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row }">
              <el-tag :key="tag.id" v-for="(tag, index) in row.spuSaleAttrValueList" closable 
                :disable-transitions="false" 
                @close="handleClose(row, index)"
              >
                {{tag.saleAttrValueName}}
              </el-tag>
              <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput" size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)">+ 添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ $index }">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="spu.spuSaleAttrList.splice($index, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      spu: {
        //三级分类ID
        category3Id: 0,
        //描述
        description: '',
        // spu名称
        spuName: '',
        //品台ID
        tmId: '',
        //收集spu图片信息
        spuImageList:[],
        //品台属性与属性值收集
        spuSaleAttrList:[]
      },
      tradeMarkList: [],
      spuImgList: [],
      saleAttrList: [],
      attrIdAndAttrName: ''
    };
  },
  methods: {
    //照片墙删除某一张图片是触发
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      //收集照片墙数据
      this.spuImageList = fileList
    },
    //照片墙图片预览事件
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //照片墙图片上传成功事件
    handleSuccess(fileList) {
      this.spuImageList = fileList
    },
    //初始化SpuForm数据
    async initSpuFormData(spu) {
      // console.log(spu);
      //获取spu信息数据
      let spuRes = await this.$API.spu.reqSpu(spu.id)
      // console.log(spuRes);
      if(spuRes.code == 200) {
        this.spu = spuRes.data
      }
      //获取品牌信息
      let tradeMarkRes = await this.$API.spu.reqTradeMarkList()
      // console.log(tradeMarkRes);
      if(tradeMarkRes.code == 200) {
        this.tradeMarkList = tradeMarkRes.data
      }
      //获取spu图片数据
      let spuImgListRes = await this.$API.spu.reqSpuInageList(spu.id)
      // console.log(spuImgListRes);
      if(spuImgListRes.code == 200) {
        let listArr = spuImgListRes.data
        //把返回的数据修改再赋值
        listArr.forEach(item => {
          item.name = item.imgName
          item.url = item.imgUrl
        });
        this.spuImgList = listArr
      }
      //获取全部的品牌销售属性
      let saleRes = await this.$API.spu.reqBaseSaleAttrList()
      // console.log(saleRes);
      if(saleRes.code == 200) {
        this.saleAttrList = saleRes.data
      }
    },
    //添加销售属性事件
    addSaleAttr() {
      //把收集到的销售属性数据进行分割
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList:[]
      }
      this.spu.spuSaleAttrList.push(newSaleAttr)
      //
      this.attrIdAndAttrName = ''
    },
    //添加销售属性的属性值按钮事件
    addSaleAttrValue(row) {
      this.$set(row, 'inputVisible', true)
      this.$set(row, 'inputValue', '')
    },
    //el-input失去焦点事件
    handleInputConfirm(row) {
      const { baseSaleAttrId, inputValue } = row
      //新增的销售属性值得名称不能为空
      if(inputValue.trim() == '') {
        this.$message('属性值不能为空')
        return
      }
      //属性值不能重复
      let result = row.spuSaleAttrValueList.some(item => item.saleAttrValueName == inputValue)
      // console.log(result);
      if(result) return

      //新增的销售属性值
      let newSaleAttrValue = {
        baseSaleAttrId,
        saleAttrValueName: inputValue
      }
      //新增
      row.spuSaleAttrValueList.push(newSaleAttrValue)

      row.inputVisible = false;
    },
    handleClose(row, index) {
      row.spuSaleAttrValueList.splice(index, 1)
    },
    //修改spu保存按钮回调
    async addOrUpdateSpu() {
      //整理参数: 需要整理照片墙的数据
      this.spu.spuImageList = this.spuImgList.map(item => {
        return {
          imageName: item.name,
          imageUrl: (item.response && item.response.data) || item.url
        }
      })
      //发请求
      let res = await this.$API.spu.reqAddOrUpdateSpu(this.spu)
      if(res.code == 200) {
        //提示
        this.$message({
          type: 'success',
          message: '保存成功'
        })
        this.$emit('changeScene', {scene: 0, flag: this.spu.id ? '修改' : '添加'})
      }
      //清楚数据
      Object.assign(this._data, this.$options.data())
    },
    //点击添加spu按钮的时候发请求的函数
    async addSpuData(category3Id) {
      this.spu.category3Id = category3Id
      //获取品牌信息
      let tradeMarkRes = await this.$API.spu.reqTradeMarkList()
      // console.log(tradeMarkRes);
      if(tradeMarkRes.code == 200) {
        this.tradeMarkList = tradeMarkRes.data
      }
      //获取全部的品牌销售属性
      let saleRes = await this.$API.spu.reqBaseSaleAttrList()
      // console.log(saleRes);
      if(saleRes.code == 200) {
        this.saleAttrList = saleRes.data
      }
    },
    //取消按钮
    cancel() {
      this.$emit('changeScene', { scene: 0, flag: ''})

      //清楚数据
      //Object.assign es6中新增的方法可以合并对象
      //this._data 可以操作data中的响应式数据
      //this.$options 可以获取组件的配置对象,配置对象中的data执行返回响应式数据为空的
      Object.assign(this._data, this.$options.data())
    }
  },
  computed: {
    unSelectSaleAttr() {
      let result = this.saleAttrList.filter(item => {
        return this.spu.spuSaleAttrList.every(item1 => {
          return item.name != item1.saleAttrName
        })
      })
      return result
    }
  }
};
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>